package siruna.WE.settings;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Klasse die de settings van een widget ophaalt en toont en bewaard
 * 
 * @author Tim
 * 
 */
public class Settings {

	// private Context mCtx;
	// private Handler mHandler;
	// private WebView mAppView;

	// alle settings in een hashmap
	private static HashMap<String, String> Text;

	// settings bestand
	private File f;

	/**
	 * Constructor
	 * 
	 * @param f
	 *            een gegeven settings bestand
	 */
	public Settings(File f) {
		this.f = f;
	}

	/**
	 * Haal de waarde op van een bepaalde string
	 * 
	 * @param name
	 *            naam
	 * @return value
	 */
	public String getValue(String name) {
		System.out.println("getvalue " + name);
		String text = getText().get(name);
		if (text != null) {
			return text;
		} else {
			return "unknown";
		}
	}

	/**
	 * Set een bepaalde waarde
	 * 
	 * @param name
	 *            naam
	 * @param value
	 *            waarde
	 */
	public void setValue(String name, String value) {
		System.out.println("setvalue " + name + " " + value);
		if (name != null && value != null) {
			getText().put(name, value);
		}
	}

	/**
	 * bouw het xml bestand terug op en bewaar het opnieuw. De nieuwe settings
	 * worden bewaard
	 * 
	 * @throws ParserConfigurationException
	 * @throws FileNotFoundException
	 */
	public void update() throws ParserConfigurationException,
			FileNotFoundException {

		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory
				.newDocumentBuilder();
		Document document = documentBuilder.newDocument();

		String root = "widget:preferences";
		Element rootElement = document.createElement(root);
		document.appendChild(rootElement);

		Collection<String> c = getText().keySet();
		Iterator<String> i = c.iterator();

		while (i.hasNext()) {
			Element em = document.createElement("preference");
			String key = i.next();
			em.setAttribute("name", key);
			em.setAttribute("type", "text");
			em.setAttribute("defaultValue", getText().get(key));
			rootElement.appendChild(em);
		}

		FileOutputStream fOut = new FileOutputStream(f);
		OutputStreamWriter osw = new OutputStreamWriter(fOut);
		try {
			System.out.println(getXml(document));
			osw.write(getXml(document));
			osw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				osw.close();
				fOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Produceer bij de huidieg naam waarde paren een gepast xml string. Deze
	 * xml wordt bewaard via de methode update().
	 * 
	 * @return xml string
	 */
	public String getXml(Node node) {
		StringBuilder buffer = new StringBuilder();

		if (node == null) {
			return "";
		}

		if (node instanceof Document) {
			buffer.append(getXml(((Document) node).getFirstChild()));
		} else if (node instanceof Element) {
			Element element = (Element) node;
			buffer.append("<");
			buffer.append(element.getNodeName() + " ");
			if (element.hasAttributes()) {
				NamedNodeMap map = element.getAttributes();
				for (int i = 0; i < map.getLength(); i++) {
					Node attr = map.item(i);
					buffer.append(attr.getNodeName());
					buffer.append("=\"");
					buffer.append(attr.getNodeValue());
					buffer.append("\" ");
				}
			}
			buffer.append(">");
			NodeList children = element.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				buffer.append(getXml(children.item(i)));
			}
			buffer.append("</");
			buffer.append(element.getNodeName());
			buffer.append(">");
		} else if (node != null && node.getNodeValue() != null) {
			buffer.append(node.getNodeValue());
		}

		return buffer.toString();
	}

	/**
	 * setter van de text hashmap
	 * 
	 * @param text
	 *            de nieuwe text hashmap
	 */
	public void setText(HashMap<String, String> text) {
		Text = text;
	}

	/**
	 * getter van de text hashmap
	 * 
	 * @return de text hashmap
	 */
	public HashMap<String, String> getText() {
		return Text;
	}

	/**
	 * Genereer op basis van de naam/waarde paren en gepast stuk html. Deze html
	 * wordt getoond aan de gebruiker als hij de settings wil instellen (of
	 * bekijken)
	 * 
	 * @param arg
	 *            naam/waarde paren
	 * @param f
	 *            deze parameter wordt niet gebruikt
	 * @return de html string
	 */
	public String generateSettings(HashMap<String, String> arg, File f) {
		HashMap<String, String> hash = arg;
		Set<String> keys = hash.keySet();

		String html = "";
		html += "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
		html += "<html xmlns='http://www.w3.org/1999/xhtml'>";
		html += "<head>";
		html += "<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>";
		html += "<title>Settings</title>";
		html += "</head>";
		html += "<script>";
		html += "function init(){";

		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			// Get element
			String v = it.next();
			html += "document.getElementById('" + v
					+ "').value = Settings.getValue('" + v + "');";
		}

		html += "}";
		html += "function updateSettings(){";

		it = keys.iterator();
		while (it.hasNext()) {
			// Get element
			String v = it.next();
			html += "Settings.setValue('" + v + "', document.getElementById('"
					+ v + "').value );";
		}

		html += "Settings.update();";
		html += "}";
		html += "</script>";

		html += "<body onload='init();'>";
		html += "<div class='toolbar'> <h1 id='pageTitle'>Settings</h1> </div>";
		html += "<div id='settings' title='Settings' class='panel'>";
		html += "<fieldset>";

		html += "<div class='row'>";

		it = keys.iterator();
		while (it.hasNext()) {
			// Get element
			String v = it.next();
			html += "<label>" + v + "</label>";
			html += "<input  name='" + v.toUpperCase() + "' id='" + v
					+ "' value='' type='text'/>";
		}
		html += "</div>  ";

		html += "<div class='row'>";
		html += "<a class='button blueButton' type='submit' onclick='updateSettings();'>Update Settings</a>";
		html += "<br/>";
		html += "<a class='button blueButton' type='submit' onclick='init();'>Reset Settings</a>";
		html += "</div> ";

		html += "</fieldset>";
		html += "</div>";
		html += "</body>";
		html += "</html>";
		return html;
	}
}
